#!/usr/bin/env node

/**
 mkdir -p /usr/local/bin/docker-tags
 wget http://dev8.cn:8000/static/ops/docker-tags.js -O /usr/local/bin/docker-tags/index.js
 chmod a+x /usr/local/bin/docker-tags/index.js
 cd /usr/local/bin/docker-tags/
 npm i shelljs
 ln -snf /usr/local/bin/docker-tags/index.js /usr/local/bin/docker-tags.js
 */

/**
 * 可以自定义比较,性能比 sort 好。
 * @param compare : 比较器，返回第1个数是否大于第2个数， 可以用 1 或 true 表示。
 */
Object.defineProperty(Array.prototype, "max", {
    value(compare) {
        compare = compare || function (a, b) {
            return a > b;
        };

        var len = this.length;
        if (!len) return null;
        var max_item = this[0];
        for (var i = 1; i < len; i++) {
            var item = this[i];
            var ret = compare(item, max_item);

            if (ret === false) {
                continue;
            }

            if (ret === true) {
                max_item = item;
            } else if (ret > 0) {
                max_item = item;
            }
        }
        return max_item;
    }, enumerable: false
});

var shell = require('shelljs');

var host = "https://registry.hub.docker.com/v1/repositories"

var args = process.argv.splice(2);

if (args.length < 1) {
    shell.echo("缺少 docker镜像 参数");
    return 1;
}

var image = args[0];
var version = args[1] || "";
var max = args[2] == "max";


if (image == "--help" || image == "-h") {
    shell.echo("docker-tags.js nginx 1.19 max")
    return 1;
}


var txt = shell.exec(`curl -s ${host}/${image}/tags`, {silent: true}).stdout

var json = JSON.parse(txt).map(it => it.name);
if (version) {
    json = json.filter(it => it.startsWith(version));
}

// 1.13.4 每部分是2位数，转换为数字： 11304
function version_2_int(v) {
    var ret = 0;
    var count = 0;
    v.split(".").slice(0, 5).forEach(it => {
        count++;
        var v = 0;
        if (/\D/.test(it) == false) {
            v = parseInt(it);
            if (isNaN(v)) {
                v = 0;
            }
        }
        ret = ret * 100 + v % 100;
    });

    while (true) {
        if (count >= 5) {
            break;
        }
        count++;

        ret = ret * 100;
    }
    return ret;
}

if (max) {
    json = [json.max((a, b) => version_2_int(a) - version_2_int(b))];
}
for (var i = 0, len = json.length; i < len; i++) {
    var item = json[i];
    shell.echo(item);
}